package system;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Scanner;

import driver.ActionDriver;
import driver.PersonDriver;

import network.client.PersonDispatcherElevatorThread;
import network.client.PersonDispatcherListener;
import network.server.ObserverPingThread;
import network.server.PersonDispatcherServerThread;

import state.Globals;

public class PersonDispatcherMain {
    
    private static boolean success = false;
    
    public static void initStatus(boolean success)
    {
        synchronized (PersonDispatcherMain.class)
        {
            PersonDispatcherMain.success = success;
            
            PersonDispatcherMain.class.notify();
        }
    }
    
    public static void main(String[] args)
    {
        
        String address = args[0];
        int port = Integer.parseInt(args[1]);
        
        GlobalData.LISTEN_PORT = Integer.parseInt(args[2]);
        
        InetAddress netAddr = null;
        
        try
        {
            netAddr = InetAddress.getByName(address);
        }
        catch (UnknownHostException e1)
        {
            e1.printStackTrace();
        }
        
        try
        {
            Globals.initLogger("Person Dispatcher");
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }        
        
        ObserverPingThread.init();
        
        ActionDriver.init();
        PersonDriver.init();
        
        PersonDispatcherServerThread t = null;
        
        try
        {
            t = new PersonDispatcherServerThread(GlobalData.LISTEN_PORT);
            t.start();
        }
        catch (IOException e1)
        {
            e1.printStackTrace();
        }
        
        GlobalData.elevatorThread = new PersonDispatcherElevatorThread(netAddr, port);
        
        synchronized (PersonDispatcherMain.class)
        {
            GlobalData.elevatorThread.start();
            
            try
            {
                PersonDispatcherMain.class.wait();
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
        
        GlobalData.elevatorThread.addListener(new PersonDispatcherListener());
        
        if (success)
        {
        
        	Scanner scan = new Scanner(System.in);
        	scan.nextLine();
        
        }
        
        // SHUTDOWN
        GlobalData.elevatorThread.shutdownThread();
        
        t.shutdownThread();
        
        ActionDriver.shutdown();
        
        ObserverPingThread.shutdown();
        
        try
        {
            Globals.getLogger().closeLogger();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        
    }
    
}
